#include "config.h"
#include "utility.h"
#include "rfile.h"
#include "myLog.h"

config::config()
{
}

config::~config()
{
}

void config::SetConfigVariable(std::string strKey, std::string strValue)
{
    char ch[255];
    std::string strContent;
    strContent = strKey + '=' + strValue;
    strcpy(ch,strContent.c_str());

    PutIntoHashTable(ch);
    TransFromHash2UserObj();
}

bool config::SaveConfig()
{
    std::string strErrorMessage;
    std::string strBackFileName, strFileName;
    strBackFileName = "_config.ini";
    strFileName = "config.ini";
    if (rfile::isExist(strBackFileName))
    {
        strmsg = "Last time is not normally close. Please check config file then delete the temp file [ " + strBackFileName + " ].";
        myLog m = myLog("config");
        m.writelog(strmsg.c_str());
        return false;
    }

    //make copy file
    if (!rfile::copyFile(strFileName.c_str(), strBackFileName.c_str(),&strErrorMessage))
    {
        strmsg = "Can't backup file, Because [ " + strErrorMessage + " ]";
        myLog m = myLog("config");
        m.writelog(strmsg.c_str());
        return false;
    }
    else
    {
		std::ofstream ofs(strFileName.c_str());
		for (map<string, string>::iterator it=ConfigData.begin(); it!=ConfigData.end(); it++)
		{
		    ofs << (*it).first << " = " << (*it).second << std::endl;
		}
		ofs.close();
		//delete temp file
		rfile::del(strBackFileName);
		return true;
    }
}

void config::PutIntoHashTable(char chr[255])
{
    if (chr[0] != '\0')
    {
        int t;
        std::string strKey, strValue;
        std::string strSetting;
        strSetting = chr;
        t = strSetting.find('=');
        if (t != -1)
        {
            strKey = strSetting.substr(0,t);
            strValue = strSetting.substr(t+1,strSetting.length());
            strKey = utility::string2upper(utility::trim(strKey));
            strValue = utility::trim(strValue);
			ConfigData[strKey] = strValue;
        }
    }
}

bool config::LoadConfig()
{
    char txt[255];
    std::ifstream inFile;

    inFile.open("config.ini");
    if (!inFile) {
        strmsg = "Unable to open config file [ config.ini ]";
        myLog m = myLog("config");
        m.writelog(strmsg.c_str());
        return false;
    }

    while(!inFile.eof())
    {
        inFile.getline(txt,255,'\n');
        PutIntoHashTable(txt);
    }
    TransFromHash2UserObj();
    inFile.close();
    return true;
}

void config::TransFromHash2UserObj()
{
    cfg.BuatRate = ConfigData["BUATRATE"];
    cfg.PortNumber = ConfigData["PORTNUMBER"];
    cfg.MaxUsersNum = ConfigData["MAXUSERSNUM"];
    cfg.Version = ConfigData["VERSION"];
}
